package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.pojos.ApAssociateWords;
import com.heima.search.service.ApAssociateWordsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {

      private final MongoTemplate mongoTemplate;

    /**
     * 联想词搜索
     * @param userSearchDto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto userSearchDto) {
        // 1、检查参数
        if(userSearchDto == null || StringUtils.isBlank(userSearchDto.getSearchWords())){
            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2、分页检查
        if(userSearchDto.getPageSize()>20){
            userSearchDto.setPageSize(20);
        }

        // 3、执行查询 (模糊查询)
        // 构建 MongoDB 查询，使用正则表达式匹配 associateWords 字段，限制返回结果的数量为 pageSize，并执行查询。
        Query query=Query.query(Criteria.where("associateWords")
                .regex(".*?\\" + userSearchDto.getSearchWords() + ".*"));
        query.limit(userSearchDto.getPageSize());
        List<ApAssociateWords> apAssociateWords = mongoTemplate.find(query, ApAssociateWords.class);
        return ResponseResult.okResult(apAssociateWords);
    }
}
